<template>
  <page-header-wrapper>
    <a-card>
      <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <p class="flex">
          <a-input class="mr-2" placeholder="请输入项目地址、客户名称、贷款顾问" style="width:30%" v-model="keyWord" />
          <a-button class="mx-4" type="primary" @click="search">查询</a-button>
          <a-button class="mr-2" @click="reset">重置</a-button>
          <ListExport :form="form" :columns="columns" :keyWord="keyWord" />
          <!-- <a-button class="mr-2" type="primary" ghost>导出数据</a-button> -->
        </p>
        <div class="flex">
          <a-form-model-item prop="dateType">
            <a-select default-value="初步协议日期" class="length mr-2" v-model="form.dateType">
              <a-select-option :value="1">
                初步协议日期
              </a-select-option>
              <a-select-option :value="2">
                初次放款日期
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-button
            v-for="(list, index) in leftPart"
            :key="index"
            class="mr-2"
            @click="durationChange(index)"
            :class="{ liBackground: changeLeftBackground == index }"
            >{{ list.name }}</a-button
          >
          <a-range-picker @change="Onchange" v-model="dateRange" />
        </div>
        <div class="flex">
          <div class="flex">
            <div class="w-20">货币：</div>
            <a-select v-model="form.currency" class="w-5 mr-8">
              <a-select-option value="全部">
                全部
              </a-select-option>
              <a-select-option value="NZD">
                NZD
              </a-select-option>
              <a-select-option value="CAD">
                CAD
              </a-select-option>
            </a-select>
          </div>
          <div class="w-70">贷款期限：</div>
          <a-input v-model="form.duration" class="length mr-2" />
          <a-select default-value="月" v-model="form.durationUnit" class="length mr-2">
            <a-select-option :value="2">
              月
            </a-select-option>
            <a-select-option :value="3">
              年
            </a-select-option>
          </a-select>

          <div class="w-70">本金额度：</div>
          <a-input class="length" v-model="form.principalGte" />——<a-input class="length" v-model="form.principalLte" />
        </div>
      </a-form-model>
    </a-card>
    <a-card>
      <a-table
        rowKey="id"
        :columns="columns"
        :data-source="data"
        :scroll="{ x: 3000, y: 400 }"
        :pagination="pagination"
        @change="sorterFun"
      >
        <span slot="addr" slot-scope="addr" class="overflow"> {{ addr }}</span>
        <span slot="agreementDate" slot-scope="agreementDate"> {{ humanizeDate(agreementDate) }}</span>
        <span slot="firstLoanTime" slot-scope="firstLoanTime"> {{ humanizeDate(firstLoanTime) }}</span>
        <span slot="sysEndTime" slot-scope="sysEndTime"> {{ humanizeDate(sysEndTime) }}</span>
        <span slot="principal" slot-scope="principal"> {{ moneyType(principal) }}</span>
        <span slot="totalLoan" slot-scope="totalLoan"> {{ moneyType(totalLoan) }}</span>
        <span slot="allIncome" slot-scope="allIncome"> {{ minMoney(allIncome) }}</span>
        <span slot="allInterest" slot-scope="allInterest"> {{ minMoney(allInterest) }}</span>
        <span slot="projectStage" slot-scope="_, record">
          <state :record="record"></state>
        </span>
        <span slot="data" slot-scope="_, record">
          <setData :record="record" @update="getData"></setData>
        </span>
        <span slot="Archive" slot-scope="_, record">
          <switchContract :record="record" @update="getData" />
        </span>
        <span slot="operation" slot-scope="_, record">
          <change :record="record" @update="getData" v-action:update2 class="mr-2"></change>
          <!-- <a-divider type="vertical" /> -->
          <a @click="toDetail(record)" v-action:get>查看</a>
        </span>
      </a-table>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { rateTypes, interestPay, interestCalc } from '@/dict'
import { getList } from '@/api/common'
import moment from 'moment'
const columns = [
  { title: '项目编号', width: 130, fixed: 'left', dataIndex: 'projectNum', key: 'projectNum' },
  {
    title: '项目地址',
    dataIndex: 'addr',
    key: 'addr',
    width: 150,
    fixed: 'left',
    sorter: true,
    sortDirections: ['ascend'],
    scopedSlots: { customRender: 'addr' }
  },
  {
    title: '客户名称',
    dataIndex: 'clientName',
    key: 'clientName',
    width: 110,
    sorter: true,
    sortDirections: ['ascend']
  },
  {
    title: '贷款顾问',
    dataIndex: 'sysUserName',
    key: 'sysUserName',
    width: 110,
    sorter: true,
    sortDirections: ['ascend']
  },
  {
    title: '初步协议签订日期',
    dataIndex: 'agreementDate',
    key: 'agreementDate',
    scopedSlots: { customRender: 'agreementDate' },
    width: 170,
    sorter: true,
    sortDirections: ['ascend']
  },
  {
    title: '开始日期',
    dataIndex: 'firstLoanTime',
    key: 'firstLoanTime',
    scopedSlots: { customRender: 'firstLoanTime' },
    width: 130,
    sorter: true,
    sortDirections: ['ascend']
  },
  {
    title: '结束日期',
    dataIndex: 'sysEndTime',
    key: 'sysEndTime',
    scopedSlots: { customRender: 'sysEndTime' },
    width: 130,
    sorter: true,
    sortDirections: ['ascend']
  },
  { title: '贷款期限', dataIndex: 'duration', key: 'duration', width: 110, sorter: true, sortDirections: ['ascend'] },
  { title: '总金额', dataIndex: 'totalLoan', key: 'totalLoan', width: 110, scopedSlots: { customRender: 'totalLoan' } },
  {
    title: '承诺金额',
    dataIndex: 'principal',
    key: 'principal',
    width: 110,
    scopedSlots: { customRender: 'principal' }
  },
  {
    title: '利息计算方式',
    dataIndex: 'interestCalcType',
    key: 'interestCalcType',
    width: 130,
    scopedSlots: { customRender: 'interestCalcType' },
    filters: [
      { text: '单利', value: 3 },
      { text: '每日复利', value: 1 },
      { text: '每月复利', value: 2 }
    ],
    filterMultiple: false
    // onFilter: (value, record) => record.loanData.interestCalcType == value
  },
  {
    title: '利息支付方式',
    dataIndex: 'interestPayType',
    key: 'interestPayType',
    scopedSlots: { customRender: 'interestPayType' },
    width: 130,
    filters: [
      { text: '月付', value: 1 },
      { text: '资本化', value: 2 }
    ],
    filterMultiple: false
    // onFilter: (value, record) => record.loanData.interestPayType == value
  },
  { title: '货币', dataIndex: 'currency', key: 'currency', width: 70 },
  { title: '利息利率(%)', dataIndex: 'rate', key: 'rate', width: 110 },
  { title: '贷款限额费', dataIndex: 'limitFeeRate', key: 'limitFeeRate', width: 110 },
  { title: '总收入', dataIndex: 'allIncome', key: 'allIncome', scopedSlots: { customRender: 'allIncome' }, width: 150 },
  {
    title: '总利息收入',
    dataIndex: 'allInterest',
    key: 'allInterest',
    scopedSlots: { customRender: 'allInterest' },
    width: 110
  },
  { title: '出借人手续费', dataIndex: 'commissionRate', key: 'commissionRate', width: 120 },
  { title: '行政费', dataIndex: 'administrativeFeeRate', key: 'administrativeFeeRate', width: 110 },
  { title: '其他费用', dataIndex: 'otherFee', key: 'otherFee', width: 110 },
  { title: '参考汇率', dataIndex: 'exrate', key: 'exrate', width: 110 },
  {
    title: '状态',
    dataIndex: 'projectStage',
    key: 'projectStage',
    scopedSlots: { customRender: 'projectStage' },
    width: 110
  },
  { title: '预期到期日', dataIndex: 'data', key: 'data', scopedSlots: { customRender: 'data' }, width: 110 },
  { title: '封存', dataIndex: 'Archive', key: 'Archive', scopedSlots: { customRender: 'Archive' }, width: 100 }
  // {
  //   title: '操作',
  //   width: 150,
  //   dataIndex: 'operation',
  //   key: 'operation',
  //   fixed: 'right',
  //   scopedSlots: { customRender: 'operation' }
  // }
]
export default {
  name: 'List',
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      keyWord: '',
      columnKey: '',
      interestCalcType: '',
      interestPayType: '',
      leftPart: [{ name: '近一周' }, { name: '近一个月' }, { name: '近三月' }, { name: '近一年' }],
      changeLeftBackground: 0,
      dateRange: [null, null],
      form: {
        dateType: 1,
        currency: '全部',
        startTime: '',
        endTime: '',
        duration: '',
        durationUnit: 2,
        principalGte: '',
        principalLte: '',
        dataType: 2,
        approve: 2,
        asseApprove: 2,
        nzApprove: 2
      },
      data: [],
      pagination: {
        total: 1,
        pageSize: 10
        // onChange: this.getData
      },
      sorterList: [
        { text: 'addr', value: 1 },
        { text: 'clientName', value: 2 },
        { text: 'sysUserName', value: 3 },
        { text: 'agreementDate', value: 5 },
        { text: 'firstLoanTime', value: 6 },
        { text: 'sysEndTime', value: 7 },
        { text: 'duration', value: 8 }
      ]
    }
  },
  computed: {
    columns() {
      if (this.$auth('manageList.update2') || this.$auth('manageList.get')) {
        return [
          ...columns,
          {
            title: '操作',
            fixed: 'right',
            width: 150,
            dataIndex: 'operation',
            key: 'operation',
            scopedSlots: { customRender: 'operation' }
          }
        ]
      } else {
        return columns
      }
    }
  },
  mounted() {
    this.getData()
    this.changeLeftBackground = -1
  },
  components: {
    change: () => import('./com/change.vue'),
    setData: () => import('./com/setEndTime.vue'),
    state: () => import('./com/listStatus.vue'),
    ListExport: () => import('./com/listExport.vue'),
    switchContract: () => import('./com/switchContract.vue')
  },
  methods: {
    reset() {
      this.keyWord = ''
      this.form.dateType = 1
      this.form.currency = '全部'
      this.form.duration = ''
      this.form.durationUnit = 2
      this.form.principalGte = ''
      this.form.principalLte = ''
      this.changeLeftBackground = -1
      this.dateRange = [null, null]
      this.getData()
    },
    durationChange(index) {
      this.changeLeftBackground = index
      if (index == 0) {
        this.dateRange = [moment(Date.now()).subtract(7, 'days'), moment(Date.now(), 'x')]
      }
      if (index == 1) {
        this.dateRange = [moment(Date.now()).subtract(1, 'months'), moment(Date.now(), 'x')]
      }
      if (index == 2) {
        this.dateRange = [moment(Date.now()).subtract(3, 'months'), moment(Date.now(), 'x')]
      }
      if (index == 3) {
        this.dateRange = [moment(Date.now()).subtract(1, 'years'), moment(Date.now(), 'x')]
      }
      this.getData()
    },
    toDetail(record) {
      this.$router.push({ name: 'manage/detail', query: { id: record.id, addr: record.addr, Archive: record.Archive } })
    },
    humanizeDate(v) {
      if (v) {
        return moment(v * 1000).format('YYYY-MM-DD') || '--'
      } else {
        return '-'
      }
    },
    moneyType(v) {
      return `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    minMoney(v) {
      if (v) {
        v = Number(v).toFixed(2)
        return `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      } else {
        return ''
      }
    },
    Onchange() {
      this.changeLeftBackground = -1
    },
    sorterFun(pagination, filters, sorter) {
      this.interestCalcType = filters.interestCalcType?.[0] ? filters.interestCalcType?.[0] : ''
      this.interestPayType = filters.interestPayType?.[0] ? filters.interestPayType?.[0] : ''
      this.columnKey = this.sorterList.find(el => el.text == sorter.columnKey)?.value
      this.getData(pagination.current)
    },
    async getData(page = 1) {
      const _form = Object.assign(
        {
          page,
          limit: this.pagination.pageSize
        },
        this.form
      )
      // console.log(this.dateRange)
      if (this.dateRange[0]) {
        _form.startTime = Number(this.dateRange[0].startOf('day').format('X'))
        _form.endTime = Number(this.dateRange[1].startOf('day').format('X'))
      }

      if (this.keyWord) {
        _form.keyWord = this.keyWord
      }
      if (this.interestCalcType) {
        _form.interestCalcType = this.interestCalcType
      }
      if (this.interestPayType) {
        _form.interestPayType = this.interestPayType
      }
      if (this.columnKey) {
        _form.orderType = this.columnKey
      }
      if (this.form.duration) {
        _form.duration = this.form.duration
        _form.durationUnit = this.form.durationUnit
      }

      if (this.form.principalGte) {
        _form.principalGte = this.form.principalGte
      }
      if (this.form.principalLte) {
        _form.principalLte = this.form.principalLte
      }
      for (let k in _form) {
        if (!_form[k]) {
          delete _form[k]
        }
      }
      if (this.form.currency == '全部') {
        delete _form.currency
      }
      if (!this.form.duration) {
        delete _form.durationUnit
      }
      const res = await getList(_form)
      const data = res.result.data
      this.pagination.total = data.total
      this.data = data.list
      if (data.list.length > 0) {
        this.data.forEach(el => {
          el.totalLoan = el.loanData.addAllLoan
          el.principal = el.loanData.addAllPrincipal
          el.currency = el.loanData.currency
          const interestPayType = el.loanData.interestPayType
          el.interestPayType = interestPay.find(el => el.value == interestPayType).text
          const interestCalcType = el.loanData.interestCalcType
          el.interestCalcType = interestCalc.find(el => el.value == interestCalcType).text
          let rate = el.loanData.rateType
          el.rate = `${rateTypes.find(el => el.value == rate).text} -${el.loanData.rate}`
          const i = el.loanData.durationUnit
          el.duration = el.loanData.duration + rateTypes.find(el => el.value == i).text
          el.sysEndTime = el.realEndTime != 0 ? el.realEndTime : el.sysEndTime
          const fee = el.loanData.fee
          fee.forEach(e => {
            if (e.feeType == 1) {
              el.limitFeeRate = e.rate
            } else if (e.feeType == 2) {
              el.commissionRate = e.rate
            } else if (e.feeType == 3) {
              el.otherFee = e.amount
            } else if (e.feeType == 4) {
              el.administrativeFeeRate = e.rate
            }
          })
        })
        this.data.agreementDate = String(this.data.agreementDate)
      }
    },
    search() {
      this.getData()
    }
  }
}
</script>
<style lang="css" scoped>
.length {
  width: 130px;
}
.liBackground {
  background: #1890ff;
  color: white;
}
.overflow {
  width: 150px;
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
/* .ant-table-fixed-header .ant-table-body-inner {
  overflow-x: auto;
  overflow-y: auto;
}
.ant-table-fixed-left,
.ant-table-fixed-left {
  height: auto !important;
  bottom: 15px;
} */
</style>
